package com.jw.blog.shiro.realms;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jw.blog.wblog.entity.Bloger;
import com.jw.blog.wblog.service.IBlogerService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author wan Email-wlf18726994755@163.com
 * @version 1.0
 * @className ShiroRealm
 * @date 2020/7/4 8:53
 **/

public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private IBlogerService iBlogerService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进来了" + token.hashCode());
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        String username = upToken.getUsername();


        //从数据库中获取用户信息
        Bloger bloger = iBlogerService.getOne(new QueryWrapper<Bloger>().lambda().eq(Bloger::getUsername,username));

        if (ObjectUtil.isNull(bloger)) {
            throw new UnknownAccountException("用户不存在");
        }

        //认证的实体信息
        Object principal = username;
        //密码
//        Object credentials = "fc1709d0a95a6be30bc5926fdb7f22f4";
        Object credentials = bloger.getPassword();

        //当前realm对象ename;
        String realmName = getName();
        //盐值
        ByteSource byteSource = ByteSource.Util.bytes(username);


        return new SimpleAuthenticationInfo(principal,credentials,byteSource,realmName);
    }

    public static void main(String[] args) {
        String hashName = "MD5";
        Object cred = "123456";
        ByteSource byteSource = ByteSource.Util.bytes("user");
        int hashInt = 1024;
        SimpleHash hash = new SimpleHash(hashName,cred,byteSource,hashInt);

        System.out.println(hash);
    }

    /**
     * 授权的会被 Shiro 回调
     * @param principals  从中获取登陆用户的信息
     * @return 获取当前用户的角色
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object principal = principals.getPrimaryPrincipal();
        Set<String> roles = new HashSet<>();
        roles.add("user");
        if ("admin".equals(principal)){
            roles.add("admin");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        return info;
    }
}
